﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using eCommerce.core;
using eCommerce.core.Helpers;
using eCommerce.db.BORespository;

namespace eCommerce.cms
{    
    public class Thumb : IHttpHandler
    {
        private int _thumbnailSize = 210;    

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(7));

            var defaultImagePath = context.Server.MapPath("/images/no-photo.jpg");
            var imagePath = context.Request.QueryString[Utils.ImagePath];
            _thumbnailSize = Utils.ToInt32(context.Request.QueryString[Utils.ThumbnailSize]);

            if (!string.IsNullOrEmpty(imagePath) && _thumbnailSize > 0)
                defaultImagePath = context.Server.MapPath(imagePath); 

            Bitmap photo = null;
            try
            {
                photo = new Bitmap(defaultImagePath);
            }
            catch // (ArgumentException) 
            {
                //throw new HttpException(404, "Photo not found.");
            }

            int width = 0, height = 0;

            if (photo != null && photo.Width > photo.Height)
            {
                width = _thumbnailSize;
                height = photo.Height * _thumbnailSize / photo.Width;
            }
            else
            {
                if (photo != null)
                {
                    width = photo.Width * _thumbnailSize / photo.Height;
                    height = _thumbnailSize;
                }
            }

            context.Response.Clear();
            var fileName = string.Format("inline; filename=ecommerce_{0}", DateTime.Now);
            context.Response.AddHeader("Content-disposition", fileName);
            context.Response.ContentType = "image/jpeg";

            try
            {
                var target = new Bitmap(width, height);

                using (var graphics = Graphics.FromImage(target))
                {
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;

                    if (photo != null) graphics.DrawImage(photo, 0, 0, width, height);

                    using (var memoryStream = new MemoryStream())
                    {
                        var info = ImageCodecInfo.GetImageEncoders();
                        var Params = new EncoderParameters(1);
                        Params.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                        context.Response.ContentType = info[1].MimeType;

                        target.Save(context.Response.OutputStream, info[1], Params);
                    }
                }
            }
            catch { }

            #region Comment                       

            /*
            var id          = Utils.ToInt32(context.Request.QueryString[Utils.Id]);
            var typeId      = Utils.ToInt32(context.Request.QueryString[Utils.TypeId]);
            _thumbnailSize  = Utils.ToInt32(context.Request.QueryString[Utils.ThumbnailSize]);

            if (id > 0 && typeId > 0)
            {
                try
                {
                    if (typeId == (int)SettingType.Category)
                    {
                        var o = CategoryBo.GetById(id);

                        if (o != null)
                        {
                            imagePath = o.ImagePath != "" && !string.IsNullOrEmpty(o.ImagePath)
                                              ? context.Server.MapPath(o.ImagePath)
                                              : context.Server.MapPath("/images/no-photo.jpg");
                        }
                    }
                    if (typeId == (int)SettingType.Product)
                    {
                        var o = ProductBo.GetById(id);

                        if (o != null)
                        {
                            imagePath = o.ImagePath != "" && !string.IsNullOrEmpty(o.ImagePath)
                                              ? context.Server.MapPath(o.ImagePath)
                                              : context.Server.MapPath("/images/no-photo.jpg");
                        }
                    }
                    else if (typeId == (int)SettingType.Article)
                    {
                        var o = ArticleBo.GetById(id);

                        if (o != null)
                        {
                            imagePath = o.ImgAvatar != "" && !string.IsNullOrEmpty(o.ImgAvatar)
                                              ? context.Server.MapPath(o.ImgAvatar)
                                              : context.Server.MapPath("/images/no-photo.jpg");
                        }
                    }
                    else if (typeId == (int)SettingType.Image)
                    {
                        var o = ImageBo.GetById(id);

                        if (o != null)
                        {
                            imagePath = o.ImagePath != "" && !string.IsNullOrEmpty(o.ImagePath)
                                              ? context.Server.MapPath(o.ImagePath)
                                              : context.Server.MapPath("/images/no-photo.jpg");
                        }
                    }
                    else if (typeId == (int)SettingType.Adv)
                    {
                        var o = AdvBo.GetById(id);

                        if (o != null)
                        {
                            imagePath = o.ImagePath != "" && !string.IsNullOrEmpty(o.ImagePath)
                                              ? context.Server.MapPath(o.ImagePath)
                                              : context.Server.MapPath("/images/no-photo.jpg");
                        }
                    }                    
                }
                catch { imagePath = context.Server.MapPath("/images/no-photo.jpg"); }
            }
            else
                imagePath = context.Server.MapPath("/images/no-photo.jpg");
            */

            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}